package mi.payment.transaction;

import lainey.ui.dialog.IconHintDialog;
import lainey.ui.dialog.TextHintDialog;
import mi.payment.MyApplication;
import mi.payment.R;
import mi.payment.constants.BaseErrorCode;
import mi.payment.constants.Params;
import mi.payment.controller.BaseController;
import mi.payment.controller.ParamsInitCtrl;
import mi.payment.db.PayDetailModel;
import mi.payment.db.UserInfoModel;
import mi.payment.db.dao.UserInfo;
import mi.payment.interfaces.ITaskListener;
import mi.payment.settings.MerManagerSettings;
import mi.payment.settings.MerchantSettingsOperation;
import mi.payment.settings.NetworkDataOperations;
import mi.payment.settings.NetworkParamSettings;
import mi.payment.settings.SystemParamsOperation;
import mi.payment.ui.base.ParentActivity;
import mi.payment.utils.NetUtils;
import mi.payment.utils.ThreadPoolManager;
import mi.payment.utils.transaction.ParamsInitTask;

public class ParamsCheckExt extends BaseController {

    private TextHintDialog mTextHintDialog;
    private IconHintDialog mSignHintDialog;

    private LogonStateListener mListener;

    public void setOnLogonStateListener(LogonStateListener l) {
        this.mListener = l;
    }

    public interface LogonStateListener {

        void onLogonSuccess();

        void onLogonFailed();

    }

    public ParamsCheckExt(ParentActivity activity) {
        super(activity);
    }

    public boolean check(boolean isNetwork, boolean isParams, boolean isLogon, boolean isTradeTimeLimit) {
        if (isNetwork) {
            isNetwork = isNotNetwork();
            if (isNetwork) return true;
        }
        if (isParams) {
            isParams = isNotCompleteParams();
            if (isParams) return true;
        }
        if (isLogon) {
            isLogon = isNotLogon();
            if (isLogon) return true;
        }
        if (isTradeTimeLimit) {
            isTradeTimeLimit = isTradeTimeLimit();
            if (isTradeTimeLimit) return true;
        }
        return false;
    }

    public boolean isNotNetwork() {
        boolean usable = NetUtils.isNetworkUsable(MyApplication.context);
        if (usable) {
            return false;
        } else {
            showTextHintDialog(R.string.ui_hint_network);
            return true;
        }
    }

    private boolean isNotCompleteParams() {
        boolean isNotComplete = isNotCompleteDefaultParams();
        if (isNotComplete) {
            showTextHintDialog(R.string.error_parameter_no_complete);
            return true;
        } else {
            return false;
        }
    }

    private boolean isNotLogon() {
        if (ParamsInitTask.isChecked) {
            return false;
        } else {
            showSignHintDialog();
            return true;
        }
    }

    private boolean isTradeTimeLimit() {
        int currentTradeCount = PayDetailModel.getInstance().getPayDetailCount();
        int maxTradeCount = SystemParamsOperation.getInstance().getSystemParamsSettings().getTransactionNumber();
        if (currentTradeCount > maxTradeCount) {
            showTextHintDialog(R.string.error_over_max_count);
            return true;
        } else {
            return false;
        }
    }

    public boolean isJudgeTradeNumber() {
        int count = PayDetailModel.getInstance().getPayDetailCount();
        if (count > 0) {
            showTextHintDialog(R.string.error_trade_count);
            return true;
        }
        return false;
    }

    public void autoLoginAndSign() {
        if (mActivity == null) return;

        boolean flag = isNotNetwork();
        if (flag) {
            showTextHintDialog(R.string.ui_hint_network);
            return;
        }

        flag = isNotCompleteParams();
        if (flag) {
            showTextHintDialog(R.string.error_parameter_no_complete);
            return;
        }

        ThreadPoolManager.executeInCachePool(
                () -> {
                    UserInfoModel.getInstance().initTable();
                    mActivity.runOnUI(
                            () -> {
                                UserInfo userInfo = UserInfoModel.getInstance().queryUserInfoById("01");
                                Params.userInfo = userInfo;
                                if (userInfo == null) {
                                    if (mListener != null) {
                                        mListener.onLogonFailed();
                                    }
                                    showToast(R.string.error_login_fail);
                                } else {
                                    if (userInfo.getUType() == 1) {
                                        startCheckIn();
                                    } else {
                                        if (mListener != null) {
                                            mListener.onLogonFailed();
                                        }
                                        showToast(R.string.error_login_fail);
                                    }
                                }
                            }
                    );
                }
        );
    }

    private void startCheckIn() {
        if (mActivity == null) return;

        ParamsInitCtrl paramsInitCtrl = new ParamsInitCtrl(mActivity);
        paramsInitCtrl.paramsInit(
                new ITaskListener<String>() {

                    @Override
                    public void onTaskSuccess(String ret) {
                        if (mListener != null) {
                            mListener.onLogonSuccess();
                        }
                        showToast(R.string.error_logon_success);
                    }

                    @Override
                    public void onTaskFailed(String ret) {
                        String code = BaseErrorCode.getCode(ret);
                        code = getString(R.string.error_logon_fail) + "  " + code;
                        showToast(code);
                        if (mListener != null) {
                            mListener.onLogonFailed();
                        }
                    }

                }
        );
    }

    /**
     * 检查默认参数
     */
    private static boolean isNotCompleteDefaultParams() {
        MerManagerSettings merchantSettings = MerchantSettingsOperation.getInstance().getMerManagerSettings();
        String merchantNum = merchantSettings.getMerchantNum();
        String terminalNum = merchantSettings.getTerminalNum();
        if (merchantNum == null || merchantNum.length() == 0) {
            return true;
        }
        if (terminalNum == null || terminalNum.length() == 0) {
            return true;
        }

        NetworkParamSettings networkSettings = NetworkDataOperations.getInstance().getNetworkParamSettings();
        String tPdu = networkSettings.getTPdu();
        String hostPort = networkSettings.getHostPort();
        String hostIpAddress = networkSettings.getHostIpAddress();
        if (tPdu == null || tPdu.length() == 0) {
            return true;
        }
        if (hostPort == null || hostPort.length() == 0) {
            return true;
        }
        if (hostIpAddress == null || hostIpAddress.length() == 0) {
            return true;
        }
        return false;
    }


    public void showSignHintDialog() {
        if (mActivity == null) return;

        if (mSignHintDialog == null) {
            mSignHintDialog = new IconHintDialog(mActivity);
            mSignHintDialog.setRightText(R.string.ok);
            mSignHintDialog.setLeftText(R.string.cancel);
            mSignHintDialog.setIconResource(R.drawable.img_warning);
            mSignHintDialog.setMessage(R.string.error_no_sign);
            mSignHintDialog.setCancelable(true);
            mSignHintDialog.setCanceledOnTouchOutside(true);
            mSignHintDialog.setLeftOnClickListener(
                    v -> dismissSignHintDialog()
            );
            mSignHintDialog.setRightOnClickListener(
                    v -> {
                        dismissSignHintDialog();
                        autoLoginAndSign();
                    }
            );
        }
        try {
            mSignHintDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showTextHintDialog(int resId) {
        if (mActivity == null) return;

        if (mTextHintDialog == null) {
            mTextHintDialog = new TextHintDialog(mActivity);
            mTextHintDialog.setOKText(R.string.ok);
            mTextHintDialog.setTitle(R.string.hint);
            mTextHintDialog.setOnClickListener(
                    v -> dismissTextHintDialog()
            );
            mTextHintDialog.setCancelable(true);
            mTextHintDialog.setCanceledOnTouchOutside(true);
        }
        try {
            mTextHintDialog.setMessage(resId);
            mTextHintDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dismissSignHintDialog() {
        if (mSignHintDialog != null) {
            try {
                mSignHintDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void dismissTextHintDialog() {
        if (mTextHintDialog != null) {
            try {
                mTextHintDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
